package db

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"gitee.com/DonHz/cloud-file-storage/db/mydb"
	"gitee.com/DonHz/cloud-file-storage/model"
	"time"
)

func SignUp(phone string, passwd string, username string) error {
	var user model.User
	res := mydb.DB.Where("phone = ?", phone).First(&user)
	if res.RowsAffected > 0 {
		return errors.New("用户已存在")
	}
	err := mydb.DB.Create(&model.User{
		Phone:    phone,
		Password: passwd,
		UserName: username,
		CreateAt: time.Now().Unix(),
		ActiveAt: time.Now().Unix(),
	}).Error
	if err != nil {
		return err
	}
	return nil
}

func SignIn(phone string, passwd string) (model.User, error) {
	var user model.User
	hash := md5.Sum([]byte(passwd))
	hashedPassword := hex.EncodeToString(hash[:])
	res := mydb.DB.Where("phone = ?", phone).First(&user)
	if res.RowsAffected == 0 {
		return model.User{}, errors.New("手机号不存在")
	}
	if user.Password != hashedPassword {
		return model.User{}, errors.New("密码错误")
	}
	return model.User{
		UserName: user.UserName,
		Phone:    user.Phone,
	}, nil
}

func UpdateToken(phone string, token string) (model.UserToken, error) {
	var userToken model.UserToken
	res := mydb.DB.Where("phone = ?", phone).First(&userToken)
	if res.RowsAffected == 0 {
		err := mydb.DB.Create(&model.UserToken{
			Phone: phone,
			Token: token,
		}).Error
		return model.UserToken{}, err
	}
	err := mydb.DB.Model(&model.UserToken{}).Where("phone =?", phone).Update("token", token).Error
	return model.UserToken{Phone: phone, Token: token}, err
}

func GetUserInfo(phone string) (User, error) {

	var user User
	res := mydb.DB.Where("phone =?", phone).First(&user)
	if res.RowsAffected == 0 {
		return User{}, errors.New("用户不存在")
	}
	return user, nil
}

type User struct {
	CreateAt int64
	ActiveAt int64
	UserName string
	Phone    string
	profile  string
}
